
import os
import sys
import shutil
import subprocess
from datetime import datetime

def setup_logging():
    """配置日志格式"""
    log_format = "%(asctime)s - %(levelname)s - %(message)s"
    logging.basicConfig(level=logging.INFO, format=log_format)

def rm_file(folder_path):
    """删除指定目录"""
    try:
        if os.path.exists(folder_path):
            shutil.rmtree(folder_path)
            logging.info(f"✅ 文件夹 {folder_path} 已删除")
        else:
            logging.warning(f"⚠️ 文件夹 {folder_path} 不存在，跳过")
    except Exception as e:
        logging.error(f"❌ 删除文件夹失败: {str(e)}")

def run_pytest(test_files, allure_dir="./allure-results"):
    """运行pytest测试"""
    command = [
        sys.executable,
        "-m", "pytest",
        "-vs",
        f"--alluredir={allure_dir}",
        *test_files
    ]
    
    try:
        logging.info("🚀 开始执行测试...")
        start_time = datetime.now()
        
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            check=True
        )
        
        # 记录执行时间
        duration = (datetime.now() - start_time).total_seconds()
        logging.info(f"🟢 测试完成，耗时: {duration:.2f}秒")
        
        if result.stdout:
            logging.debug("测试输出:\n" + result.stdout)
    except subprocess.CalledProcessError as e:
        logging.error(f"🔴 测试执行失败:\n{e.stderr}")
        raise
    except Exception as e:
        logging.error(f"❌ 未知错误: {str(e)}")
        raise

def show_allure(allure_dir="./allure-results", port=8080):
    """启动Allure服务"""
    try:
        logging.info(f"🌐 启动Allure报告服务，端口: {port}")
        subprocess.run(
            ["allure", "serve", allure_dir, "--port", str(port)],
            check=True
        )
    except FileNotFoundError:
        logging.error("❌ Allure未安装，请先安装: pip install allure-pytest")
        raise
    except subprocess.CalledProcessError as e:
        logging.error(f"❌ Allure服务启动失败: {str(e)}")
        raise

def main():
    # 配置参数
    CONFIG = {
        "allure_dir": r"D:\Gitee\temperature_-monitoring\allure-results",
        "test_files": [
            "testcases/test_login.py",
            "testcases/test_home.py",
            "testcases/test_Statistics.py",
            "testcases/test_monitor.py",
            "testcases/test_history.py",
            "testcases/test_alarm.py",
            "testcases/test_runreport.py",
            "testcases/test_userlist.py"
        ],
        "allure_port": 8080
    }
    
    try:
        setup_logging()
        
        # 1. 清理旧报告
        rm_file(CONFIG["allure_dir"])
        
        # 2. 运行测试
        run_pytest(
            test_files=CONFIG["test_files"],
            allure_dir=CONFIG["allure_dir"]
        )
        
        # 3. 生成报告
        show_allure(
            allure_dir=CONFIG["allure_dir"],
            port=CONFIG["allure_port"]
        )
        
    except Exception as e:
        logging.error(f"🔴 主流程执行失败: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    import logging
    main()